<?php

namespace app\api\service\order\paysuccess\type;

use app\api\model\user\User as UserModel;
use app\common\enum\order\OrderPayTypeEnum;
use app\common\enum\user\balanceLog\BalanceLogSceneEnum;
use app\common\model\user\BalanceLog;
use app\common\model\user\GradeLog;
use app\common\service\award\AwardService;
use app\common\service\BaseService;
use app\shop\model\plus\model\AgentSet;
/**
 * 等级支付成功后的回调
 */
class GradePaySuccessService extends BaseService
{
    // 订单模型
    public $model;

    // 当前用户信息
    private $user;

    /**
     * 构造函数
     */
    public function __construct($orderNo, $pay_status = 0)
    {
        // 实例化订单模型
        $this->model = GradeLog::getPayDetail($orderNo, $pay_status);
        // 获取用户信息
        $this->user = UserModel::detail($this->model['user_id']);
    }

    /**
     * 返回app_id，大于0则存在订单信息
     */
    public function isExist()
    {
        if ($this->model) {
            return $this->model['app_id'];
        }
        return 0;
    }
    /**
     * 订单支付成功业务处理
     */
    public function onPaySuccess($payType, $payData = [])
    {
        if (empty($this->model)) {
            $this->error = '未找到该订单信息';
            return false;
        }
        // 更新付款状态
        return $this->updatePayStatus($payType, $payData);
    }

    /**
     * 更新付款状态
     */
    private function updatePayStatus($payType, $payData = [])
    {
        // 事务处理
        $this->model->transaction(function () use ($payType, $payData) {
            // 更新订单状态
            $this->updateOrderInfo($payType, $payData);
            // 记录订单支付信息
            $this->updatePayInfo($payType);
            //发放奖励
            $this->payCommission();
        });
        return true;
    }

    /**
     * 更新订单记录
     */
    private function updateOrderInfo($payType, $payData)
    {
        $order = [
            'pay_type' => $payType,
            'change_status' => 1,
            'pay_time' => time(),
        ];
        if ($payType == OrderPayTypeEnum::WECHAT) {
            $order['trade_id'] = $payData['transaction_id'] ?? "";
        }
        // 更新订单状态
        return $this->model->save($order);
    }

    /**
     * 记录订单支付信息
     */
    private function updatePayInfo($payType)
    {
        // 更新用户等级
        $new_grade = $this->model->new_grade_id;
        $grade_type = $this->model->grade['grade_expired_type'];
        switch ($grade_type) {
            case 1: //年级
                $expired = strtotime("+1 year");
                break;
            case 2: //月级
                $expired = strtotime("+1 month");
                break;
            default:    //永久
                $expired = 0;
        }
        (new UserModel())->where('user_id', '=', $this->user['user_id'])
            //->inc('balance', $this->model['real_money'])
            ->save([
                'grade_id' => $new_grade,
                'grade_expired' => $expired,
            ]);
    }

    /**
     * 发放奖励
     */
    private function payCommission()
    {
        $AwardService = new AwardService();
        $agent_award = $AwardService->agentAward($this->user, $this->model['price']);
        foreach ($agent_award as $v) {
            (new UserModel())->where('user_id', '=', $v['user_id'])
                ->inc('balance', $v['money'])
                ->save();
            //增加余额记录
            $user_name = $this->user['nickName'] ?? $this->user['real_name'];
            $grade_name = $this->model['grade']['name'];
            BalanceLog::add(BalanceLogSceneEnum::RECOMMEND_BUY_MEMBER, [
                'user_id' => $v['user_id'],
                'money' => $v['money'],
                'scene_id' => $this->model['log_id'],
            ], [$user_name . "->" . $grade_name]);
        }
        return true;
    }
}